<template>
  <div>
    <FixedOperation>
      <el-row>
        <el-col :offset="20" :span="4" class="flex justify-end">
          <el-button plain type="primary" @click="submit">保存</el-button>
          <el-button plain type="primary" @click="goBack">返回</el-button>
        </el-col>
      </el-row>
    </FixedOperation>
    <div v-loading="loading" class="newContract app-container">
      <div class="requiredTip">
        <span class="text-red-500">*</span> 为必填项
      </div>
      <el-form
        id="newContractForm"
        ref="baseForm"
        :inline="true"
        :model="newContractForm"
        :rules="rules"
      >
        <div class="part">
          <title-name
            icon="i-carbon-bookmark-filled"
            title="合同主体信息"
          ></title-name>
          <el-row class="justify-center mt-10px">
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="合同甲方:"
                  label-width="180px"
                  prop="partyaName"
                  style="width: 80%"
                >
                  <el-input
                    v-model="newContractForm.partyaName"
                    :disabled="
                      isFromProject
                        ? ''
                        : businessParams.type &&
                          businessParams.type == 'business'
                    "
                    placeholder="请选择合同甲方"
                    @focus="activatePartya"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="甲方签约人:"
                  label-width="180px"
                  prop="partyaSig"
                  style="width: 80%"
                >
                  <el-input
                    v-model="newContractForm.partyaSig"
                    placeholder="请输入甲方签约人"
                  ></el-input
                ></el-form-item>
              </el-row>
            </el-col>
          </el-row>
          <el-row class="justify-center">
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="合同乙方:"
                  label-width="180px"
                  prop="partybName"
                  style="width: 80%"
                >
                  <el-input
                    v-model="newContractForm.partybName"
                    placeholder="请选择合同乙方"
                    @focus="activatePartyb"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="乙方签约人:"
                  label-width="180px"
                  prop="partybSig"
                  style="width: 80%"
                >
                  <el-input
                    v-model="newContractForm.partybSig"
                    placeholder="请输入乙方签约人"
                  ></el-input
                ></el-form-item>
              </el-row>
            </el-col>
          </el-row>
        </div>
        <!-- 基础表单 -->
        <div class="part">
          <title-name
            icon="i-carbon-bookmark-filled"
            title="基本信息"
          ></title-name>
          <el-row class="justify-around mt-10px">
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="合同名称:"
                  label-width="180px"
                  prop="contractName"
                  style="width: 80%"
                >
                  <el-input
                    v-model="newContractForm.contractName"
                    placeholder="请输入合同名称"
                  ></el-input>
                </el-form-item>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="合同编号:"
                  label-width="180px"
                  prop="contractNum"
                  style="width: 80%"
                >
                  <el-input
                    v-model="newContractForm.contractNum"
                    placeholder="请输入合同编号"
                  ></el-input
                ></el-form-item>
              </el-row>
            </el-col>
          </el-row>

          <el-row class="justify-center">
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="合同金额:"
                  label-width="180px"
                  prop="contractSum"
                  style="width: 80%"
                >
                  <el-input
                    v-model="newContractForm.contractSum"
                    placeholder="请输入合同金额"
                    @blur="blurAmount('contractSum')"
                    @input="val => changeAmount('contractSum', val)"
                    ><template #append>元</template></el-input
                  ></el-form-item
                >
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="合同类别:"
                  label-width="180px"
                  prop="contractType"
                  style="width: 80%"
                >
                  <el-tree-select
                    v-model="newContractForm.contractType"
                    :data="businessAttribute"
                    :render-after-expand="false"
                    clearable
                    default-expand-all
                  />
                </el-form-item>
              </el-row>
            </el-col>
          </el-row>
          <el-row class="justify-center">
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="所属业务分类:"
                  label-width="180px"
                  prop="businessCategorize"
                  style="width: 80%"
                >
                  <el-tree-select
                    v-model="newContractForm.businessCategorize"
                    :data="businessTypeOption"
                    placeholder="请选择业务分类"
                    @change="changeBusinessType"
                  />
                </el-form-item>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="合同性质:"
                  label-width="180px"
                  prop="contractAttribute"
                  style="width: 80%"
                >
                  <el-radio-group
                    v-model="newContractForm.contractAttribute"
                    class="ml-4"
                  >
                    <el-radio label="1" size="large">销售合同</el-radio>
                    <el-radio label="2" size="large">采购合同</el-radio>
                  </el-radio-group>
                </el-form-item></el-row
              ></el-col
            >
          </el-row>

          <el-row class="justify-center">
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="合同时间起:"
                  label-width="180px"
                  prop="contractTimeBegin"
                  style="width: 80%"
                >
                  <el-date-picker
                    v-model="newContractForm.contractTimeBegin"
                    placeholder="开始日期"
                    type="date"
                    value-format="YYYY-MM-DD"
                /></el-form-item>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="合同时间止:"
                  label-width="180px"
                  prop="contractTimeEnd"
                  style="width: 80%"
                >
                  <el-date-picker
                    v-model="newContractForm.contractTimeEnd"
                    placeholder="结束日期"
                    type="date"
                    value-format="YYYY-MM-DD"
                /></el-form-item>
              </el-row>
            </el-col>
          </el-row>

          <el-row class="justify-center">
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="签约时间:"
                  label-width="180px"
                  prop="sinTime"
                  style="width: 80%"
                >
                  <el-date-picker
                    v-model="newContractForm.sinTime"
                    placeholder="请输入合同签约时间"
                    type="date"
                    value-format="YYYY-MM-DD"
                /></el-form-item>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="销售人员:"
                  label-width="180px"
                  prop="salesmanId"
                  style="width: 80%"
                >
                  <el-input
                    v-model="saler"
                    placeholder="销售人员"
                    @focus="salerSaleDialog"
                  ></el-input>
                  <SelectDialog
                    :dialog-param="SaleDialog"
                    @close="SaleDialog.isDialog = false"
                    @ok="selectSales"
                  />
                </el-form-item>
              </el-row>
            </el-col>
          </el-row>
          <!--   根据规则自动填写  -->
          <!-- <el-row class="justify-center">
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label-width="180px"
                  style="width: 80%"
                  label="所属产业:"
                  prop="industry"
                >
                  <el-select
                    v-model="newContractForm.industry"
                    placeholder="请选择所属产业"
                    clearable
                  >
                    <el-option
                      v-for="(dict, index) in affiliation_industry"
                      :key="index"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option></el-select
                ></el-form-item>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label-width="180px"
                  style="width: 80%"
                  label="业务分类:"
                  prop="businessClassify"
                >
                  <el-select
                    v-model="newContractForm.businessClassify"
                    placeholder="请选择业务分类"
                    clearable
                  >
                    <el-option
                      v-for="(dict, index) in business_classification"
                      :key="index"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option></el-select
                ></el-form-item>
              </el-row>
            </el-col>
          </el-row> -->

          <el-row class="justify-center">
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="关联订单:"
                  label-width="180px"
                  prop="ordOrderContractEntitys"
                  style="width: 80%"
                >
                  <el-select
                    v-model="ordOrderContractEntitys"
                    clearable
                    multiple
                    placeholder="请输入订单名称"
                    @focus="activeOrdDialog"
                  >
                    <el-option
                      v-for="item in optionsOrder"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    /> </el-select
                ></el-form-item>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="关联项目:"
                  label-width="180px"
                  prop="ordProjectId"
                  style="width: 80%"
                >
                  <el-input
                    v-model="ordProjectName"
                    :disabled="isFromProject"
                    clearable
                    placeholder="请选择关联项目"
                    @clear="clearAll('project')"
                    @click="activeDialog('project')"
                  ></el-input>
                  <RelatedProject
                    :relatedParams="proParams"
                    @closeDialog="proCloseDialog('project')"
                    @relatedOver="proRelatedOver"
                  />
                </el-form-item>
              </el-row>
            </el-col>
          </el-row>
          <el-row class="justify-center">
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="关联商机:"
                  label-width="180px"
                  prop="titleName"
                  style="width: 80%"
                >
                  <el-input
                    v-model="newContractForm.businessOpportunityTitle"
                    :disabled="
                      businessParams.type && businessParams.type == 'business'
                    "
                    clearable
                    placeholder="请选择关联商机"
                    @clear="clearAll('business')"
                    @click="activeDialog('business')"
                  ></el-input>
                  <RelatedBusiness
                    :relatedParams="businessDiaParams"
                    @closeDialog="proCloseDialog('business')"
                    @relatedOver="businessDiaRelatedOver"
                  />
                </el-form-item>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-form-item
                  label="履约保证金是否单独支付:"
                  label-width="180px"
                  prop="pbAlonePay"
                  style="width: 80%"
                >
                  <el-radio-group
                    v-model="newContractForm.pbAlonePay"
                    class="ml-4"
                  >
                    <el-radio label="1" size="large">是</el-radio>
                    <el-radio label="2" size="large">否</el-radio>
                  </el-radio-group></el-form-item
                >
              </el-row>
            </el-col>
            <el-col :span="24">
              <el-row>
                <el-form-item
                  label="履约保证金:"
                  label-width="180px"
                  prop="pb"
                  style="width: 40%"
                >
                  <el-input
                    v-model="newContractForm.pb"
                    placeholder="请输入履约保证金"
                    @blur="blurAmount('pb')"
                    @input="val => changeAmount('pb', val)"
                    ><template #append>元</template></el-input
                  ></el-form-item
                >
              </el-row>
            </el-col>
          </el-row>
          <el-row class="mb-20px" style="width: 100%">
            <el-col :span="24">
              <el-row>
                <el-form-item
                  label="合同标的内容说明:"
                  label-width="180px"
                  prop="remark"
                  style="width: 90%"
                >
                  <el-input
                    v-model="newContractForm.remark"
                    :rows="5"
                    maxlength="500"
                    placeholder="输入合同标的内容说明"
                    show-word-limit
                    type="textarea"
                /></el-form-item>
              </el-row>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div class="part">
        <title-name
          icon="i-carbon-bookmark-filled"
          title="合同附件"
        ></title-name>
        <el-row class="pb-15px htfj mt-10px">
          <el-col :span="20">
            <el-row style="width: 80%">
              <el-form-item
                label="合同附件:"
                label-width="180px"
                prop="fileNames"
                style="width: 80%"
              >
                <el-upload
                  :before-upload="beforeAvatarUpload"
                  :http-request="handleFileChange"
                  :multiple="true"
                  :show-file-list="false"
                  accept=".rar, .zip, .doc, .docx, .pdf"
                  action="#"
                  class="upload-demo"
                >
                  <el-button style="font-size: 14px" type="primary"
                    ><el-icon> <UploadFilled /> </el-icon>上传合同</el-button
                  >
                  <template #tip>
                    <div class="el-upload__tip float-right ml-5px">
                      支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
                    </div>
                  </template>
                </el-upload>
                <div class="text-14px mt-10px" style="width: 100%">
                  <div v-for="(item, index) in fileList" :key="item.fileId">
                    <a :href="item.url" style="color: #409eff">{{
                      item.origFileName
                    }}</a>
                    <el-button plain text @click="delFileName(index)"
                      >删除</el-button
                    >
                  </div>
                </div>
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
      </div>

      <!-- 人力外包情况 -->
      <div v-if="epiboly" class="part checkPlan">
        <title-name
          icon="i-carbon-bookmark-filled"
          title="人力外包情况"
        ></title-name>
        <EditTable
          ref="crudEpiboly"
          :actionBarForSave="actionBarForSaveWb"
          :data="epibolyData"
          :option="epibolyOption"
          :statistics="numSUm"
          :width="'80%'"
          @rowDelete="epibolyRowDelete"
          @rowSave="epibolyRowSave"
        >
          <template v-slot:selfDefined>
            <el-button
              icon="el-icon-plus"
              type="primary"
              @click="rowAdd('crudEpiboly')"
              >新增</el-button
            >
          </template>
        </EditTable>
      </div>
      <!-- 项目验收计划 -->
      <div class="part checkPlan">
        <title-name
          icon="i-carbon-bookmark-filled"
          title="付款方式和条款"
        ></title-name>
        <EditTable
          ref="crud"
          :actionBarForSave="actionBarForSaveYs"
          :data="checkData"
          :option="checkOption"
          :statistics="amountSum"
          :width="'80%'"
          @rowClick="handleRowClick"
          @rowDelete="rowDelete"
          @rowSave="rowSave"
        >
          <template v-slot:selfDefined>
            <el-button
              icon="el-icon-plus"
              type="primary"
              @click="rowAdd('crud')"
              >新增</el-button
            >
          </template>
          <template #footerForm>
            <el-row class="statisticsFrom">
              <el-col :span="12" class="justify-center">
                <el-row>
                  <el-col :span="4" class="font-15">验收提醒:</el-col>
                  <el-col :span="20">
                    <el-select v-model="checkList.followTip" clearable>
                      <el-option
                        v-for="(item, index) in reminder_opening"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select> </el-col></el-row
              ></el-col>

              <el-col :span="12" class="justify-center">
                <el-row>
                  <el-col :span="4" class="font-15">通知人员:</el-col>
                  <el-col :span="20">
                    <el-input
                      v-model="NotifyingOfficer"
                      placeholder="通知人员"
                      @click="Notifyingdialog.isDialog = true"
                    ></el-input>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="12" class="justify-center mt-20px">
                <el-row>
                  <el-col :span="4" class="font-15"> 提醒方式: </el-col>
                  <el-col :span="20">
                    <el-checkbox-group v-model="checkList.list">
                      <el-checkbox
                        v-for="(dict, index) in reminder_method"
                        :key="index"
                        :label="dict.value"
                      >
                        {{ dict.label }}</el-checkbox
                      >
                    </el-checkbox-group></el-col
                  >
                </el-row>
              </el-col>
            </el-row>
          </template>
        </EditTable>
      </div>
      <!-- 履约保证金跟进任务 -->
      <div
        v-show="Number(newContractForm.pbAlonePay) === 1"
        class="part earnesMoney mb-40px"
      >
        <title-name
          icon="i-carbon-bookmark-filled"
          title="履约保证金跟进任务"
        ></title-name>
        <el-row class="mt-20px statisticsFrom">
          <el-col :span="12">
            <el-row>
              <el-col :span="4" class="font-15">天数:</el-col>
              <el-col :span="20" class="flex items-center">
                <el-select
                  v-model="earnestMoney.date"
                  class="smallInput"
                  @change="val => changeDay(val, 'pb')"
                >
                  <el-option label="工作日" value="0"> </el-option>
                  <el-option label="自然日" value="1"> </el-option>
                </el-select>
                <el-input-number
                  v-model="earnestMoney.num"
                  :min="1"
                  controls-position="right"
                  @change="val => timeChange(val, 'pb')"
                />
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="4" class="font-15 pbTip"> 跟进人员:</el-col>
              <el-col :span="20">
                <el-input
                  v-model="person"
                  placeholder="跟进人员"
                  @click="dialogParam.isDialog = true"
                ></el-input>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row class="mt-20px statisticsFrom">
          <el-col :span="12">
            <el-row>
              <el-col :span="4" class="font-15 pbTip"> 跟进时间:</el-col>
              <el-col :span="20">
                <el-date-picker
                  v-model="earnestMoney.time"
                  :shortcuts="shortcuts"
                  placeholder="选择日期"
                  type="date"
                  value-format="YYYY-MM-DD"
                />
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="4" class="font-15 pbTip"> 提醒方式: </el-col>
              <el-col :span="20">
                <el-checkbox-group v-model="earnestMoney.list">
                  <el-checkbox
                    v-for="(dict, index) in reminder_method"
                    :key="index"
                    :label="dict.value"
                  >
                    {{ dict.label }}</el-checkbox
                  >
                </el-checkbox-group></el-col
              >
            </el-row>
          </el-col>
        </el-row>
      </div>
    </div>
    <el-dialog
      v-model="timeVisible"
      :before-close="handleClose"
      :destroy-on-close="true"
      class="timeDiglog"
      title="日期计算"
      width="30%"
    >
      <el-row>
        <el-col :span="6" class="timeCalc">天数:</el-col>
        <el-col :span="18" class="flex items-center">
          <el-select
            v-model="calcTime.date"
            class="smallInput"
            @change="val => changeDay(val)"
          >
            <el-option label="工作日" value="0"> </el-option>
            <el-option label="自然日" value="1"> </el-option>
          </el-select>
          <el-input-number
            v-model="calcTime.num"
            :min="1"
            controls-position="right"
            @change="val => timeChange(val)"
          />
        </el-col>
      </el-row>
      <el-row class="mt-20px">
        <el-col :span="6" class="timeCalc">
          <span class="text-red-500 pr-5px">*</span> 验收时间:</el-col
        >
        <el-col :span="18" class="flex items-center">
          <el-date-picker
            v-model="calcTime.time"
            :shortcuts="shortcuts"
            placeholder="验收时间"
            type="date"
            value-format="YYYY-MM-DD"
          />
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="setTime"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <SelectDialog
      :dialog-param="dialogParam"
      @close="dialogParam.isDialog = false"
      @ok="selectData"
    />
    <SelectDialog
      :dialog-param="Notifyingdialog"
      @close="Notifyingdialog.isDialog = false"
      @ok="selectNotifying"
    />
    <RelatedOrder
      :relatedParams="orderParams"
      @closeDialog="ordCloseDialog"
      @relatedOver="ordRelatedOver"
    />
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @close="closeDialogA"
      @ok="selectPartya"
    />
    <SelectCustomer
      v-if="dialogParamB.isDialog"
      :dialog-param="dialogParamB"
      @close="closeDialogB"
      @ok="selectPartyb"
    />
  </div>
</template>

<script name="NewContract" setup>
import EditTable from './EditTable.vue'
import {
  reminder_opening, //开标提醒(提醒时间)
  reminder_method
} from '@/hooks/dict/useProject'
import {
  order_business_type,
  userBusinessTypeOption,
  businessTypeOption,
  businessParams
} from '@/hooks/dict/order'
import {
  business_classification,
  affiliation_industry
} from '@/hooks/dict/contract'
import TitleName from '@/components/TitleName'
import { epiboly_work_type } from '@/hooks/dict/contract'
import useCommonStore from '@/store/modules/common'
import {
  epibolySave,
  epibolyDelete,
  epibolyUpdate,
  checkProSave,
  checkProDelete,
  checkProUpdate,
  contractInfoSave,
  uploadFile,
  delFile,
  contractDetails,
  contractInfoUpdate,
  getOrderList
} from '@/api/salesManage/contractManage'
import { pushNotifications } from '@/hooks/notification/push'
import { getWorkDay, getLatestMsg, addManage } from '@/api/system/notice'
import { format } from 'date-fns'
import useUserStore from '@/store/modules/user'
import useTagsViewStore from '@/store/modules/tagsView'
import { handleTree } from '@/utils/ruoyi'
const commonStore = useCommonStore()
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const shortcuts = [
  {
    text: '今天',
    value: new Date()
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    }
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    }
  }
]
const amountSum = [
  {
    label: '总计划期数',
    key: 'periodsNum',
    type: 'length',
    unit: '期',
    unitPlace: 'after'
  },
  {
    label: '总回款占比',
    key: 'planAccepRatio',
    type: 'sum',
    unit: '%',
    unitPlace: 'after'
  },
  {
    label: '总金额',
    key: 'planReturnSum',
    type: 'sum',
    unit: '￥',
    unitPlace: 'before'
  }
]

const numSUm = [
  {
    label: '总人数',
    key: 'peopleNum',
    type: 'sum',
    unit: '人',
    unitPlace: 'after'
  }
]

// 设置计划验收日期弹窗
const timeVisible = ref(false)
// 选择行
const indexRow = ref('0')
// 跟进人员 label
const person = ref()
// 通知人员 label
const NotifyingOfficer = ref()
// 销售人员 label
const saler = ref()
// 判断新建或编辑
const isAdd = ref(!!location.href.match(/newContract/))
// 合同ID
const rcId = ref()
// 公司列表
const companyList = ref(null)
// 外部客户id
// const customeId = ref()
// 判断合同甲方选择客户还是内部
const partyaIs = ref(false)
// 判断合同乙方选择客户还是内部
const partybIs = ref(false)
// 判断是否执行消息添加
const checkAdd = ref(false)
const pbAdd = ref(false)
const actionBarForSaveWb = ref(false)
const actionBarForSaveYs = ref(false)
const useTree = ref(null)
const data = reactive({
  checkMsgData: [],
  pbMsgData: {},
  newContractForm: {
    contractName: null,
    contractNum: null,
    businessType: '2',
    contractSum: null,
    pb: null,
    pbAlonePay: '2',
    partya: null,
    partyaSig: null,
    partyb: null,
    partybSig: null,
    ordProjectId: null,
    contractTimeBegin: null,
    contractTimeEnd: null,
    salesmanId: null,
    sinTime: null,
    remark: null,
    fileNames: [],
    ordProjectCheckEntity: [], // 验收计划数据
    ordHroEntity: [], // 人力外包数据
    ordOrderContractEntitys: [], // 关联订单数据
    customerId: '', // 客户ID
    customerName: '', // 名称
    businessClassify: null, // 业务分类
    industry: null, // 所属产业
    contractType: '2', //合同类别
    contractLevel: '航天科工外',
    cusType: 'customer',
    contractAttribute: '1' // 合同性质
  },
  ordOrderContractEntitys: [], // 订单id
  optionsOrder: [],
  checkData: [],
  checkOption: {
    align: 'center',
    border: true,
    delBtn: false,
    columnBtn: false,
    editBtn: false,
    cancelBtn: false,
    addBtn: false,
    refreshBtn: false,
    // emptyText: '暂无验收计划数据',
    column: [
      {
        label: '序号',
        prop: 'periodsNum',
        width: '80'
      },
      {
        label: '阶段',
        prop: 'stage',
        cell: true,
        placeholder: '请输入阶段',
        width: '180'
        // rules: [
        //   {
        //     required: true,
        //     message: '请输入阶段',
        //     trigger: 'blur'
        //   }
        // ]
      },
      {
        label: '条件',
        prop: 'conditions',
        cell: true,
        placeholder: '请输入条件',
        width: '180'
        // rules: [
        //   {
        //     required: true,
        //     message: '请输入条件',
        //     trigger: 'blur'
        //   }
        // ]
      },
      {
        label: '付款日期',
        prop: 'planAccepDate',
        width: '180',
        cell: true,
        change: row => {
          if (!newContractForm.value.sinTime) {
            nextTick(() => {
              row.row.planAccepDate = null
            })
          }
        },
        placeholder: '请输入付款日期'
        // rules: [
        //   {
        //     required: true,
        //     message: '请输入付款日期',
        //     trigger: 'blur'
        //   }
        // ]
      },
      {
        label: '付款金额比例(%)',
        prop: 'planAccepRatio',
        // dataType: 'number',
        cell: true,
        type: 'number',
        placeholder: '请输入付款金额比例',
        width: '180',
        change: val => {
          console.log(val, '111111')
          if (newContractForm.value.contractSum) {
            if (val.value) {
              val.row.planReturnSum =
                (newContractForm.value.contractSum * val.value) / 100
            } else {
              val.row.planReturnSum = null
            }
          }
        }
      },
      {
        label: '付款金额(元)',
        prop: 'planReturnSum',
        type: 'number',
        cell: true,
        placeholder: '请输入付款金额',
        width: '180'
        // rules: [
        //   {
        //     required: true,
        //     message: '请输入付款金额',
        //     trigger: 'blur'
        //   }
        // ]
      },
      {
        label: '备注',
        prop: 'remark',
        cell: true,
        placeholder: '请输入备注',
        width: '180'
      }
    ]
  },
  // 保证金参数
  earnestMoney: {
    date: '0',
    num: null,
    receiver: null,
    time: null,
    // followTip: null,
    list: ['0'],
    content: null
  },
  // 验收计划表格
  checkList: {
    followTip: null,
    list: ['0'],
    receiver: null
  },
  // 计划验收日期
  calcTime: {
    date: '0',
    time: '',
    num: null
  },
  epibolyOption: {
    align: 'center',
    border: true,
    delBtn: false,
    columnBtn: false,
    editBtn: false,
    cellBtn: false,
    cancelBtn: false,
    addBtn: false,
    refreshBtn: false,
    // emptyText: '暂无人力外包数据',
    column: [
      {
        label: '工种',
        prop: 'workType',
        cell: true,
        type: 'select',
        dicData: epiboly_work_type,
        placeholder: '请输入工种'
      },
      {
        label: '人数',
        prop: 'peopleNum',
        cell: true,
        type: 'number',
        placeholder: '请输入人数'
      }
    ]
  },
  epibolyData: [],
  dialogParam: {},
  Notifyingdialog: {},
  SaleDialog: {},
  fileList: [], // 上传文件列表
  dialogParamA: {},
  dialogParamB: {},
  rules: {
    businessCategorize: [
      {
        required: true,
        message: '请选择所属业务分类',
        trigger: ['blur', 'change']
      }
    ],
    contractAttribute: [
      { required: true, message: '请选择合同性质', trigger: ['blur', 'change'] }
    ],
    contractName: [
      { required: true, message: '请输入合同名称', trigger: ['blur', 'change'] }
    ],
    contractNum: [
      { required: true, message: '请输入合同编号', trigger: ['blur', 'change'] }
    ],
    // businessType: '2',
    contractSum: [
      { required: true, message: '请输入合同金额', trigger: ['blur', 'change'] }
    ],
    // pb: null,
    // pbAlonePay: '1',
    partyaName: [
      {
        required: true,
        message: '请选择甲方',
        trigger: 'change'
      }
    ],
    partyaSig: [
      { required: true, message: '请输入甲方签约人', trigger: 'blur' }
    ],
    partybName: [
      {
        required: true,
        message: '请选择乙方',
        trigger: 'change'
      }
    ],
    partybSig: [
      {
        required: true,
        message: '请输入乙方签约人',
        trigger: ['blur', 'change']
      }
    ],
    // ordProjectId: null,
    contractTimeBegin: [
      {
        required: true,
        message: '请选择合同时间起',
        trigger: 'blur'
      }
    ],
    contractTimeEnd: [
      {
        required: true,
        message: '请选择合同时间止',
        trigger: ['blur', 'change']
      }
    ],
    // fileNames: [{ required: true, message: '请上传合同', trigger: 'change' }],
    // salesmanId: null,
    sinTime: [
      { required: true, message: '请选择签约时间', trigger: ['blur', 'change'] }
    ],
    // businessClassify: [
    //   { required: true, message: '请选择业务分类', trigger: ['blur', 'change'] }
    // ],
    // industry: [
    //   { required: true, message: '请选择所属产业', trigger: ['blur', 'change'] }
    // ],
    remark: [
      {
        required: true,
        message: '请输入合同标的内容说明',
        trigger: ['blur', 'change']
      }
    ]
    // fileNames: [],
    // ordProjectCheckEntity: [], // 验收计划数据
    // ordHroEntity: [], // 人力外包数据
    // ordOrderContractEntitys: [], // 关联订单数据
    // customerId: '', // 客户ID
    // customerName: '' // 名称
  },
  tableData: [
    {
      type: '甲方',
      name: '',
      person: ''
    },
    {
      type: '乙方',
      name: '',
      person: ''
    }
  ],
  businessAttribute: []
})

const {
  newContractForm,
  ordOrderContractEntitys,
  checkData,
  checkOption,
  earnestMoney,
  checkList,
  calcTime,
  epibolyOption,
  epibolyData,
  dialogParam,
  Notifyingdialog,
  SaleDialog,
  fileList,
  dialogParamA,
  dialogParamB,
  rules,
  checkMsgData,
  pbMsgData,
  optionsOrder,
  businessAttribute
} = toRefs(data)

const props = defineProps({
  id: {
    type: String,
    default: ''
  }
})
const ordProjectName = ref('')
const loading = ref(true)
async function init() {
  actionBarForSaveWb.value = false
  actionBarForSaveYs.value = false
  if (!isAdd.value) {
    actionBarForSaveWb.value = true
    actionBarForSaveYs.value = true
    rcId.value = props.id
    try {
      // 获取合同信息
      const contractData = await contractDetails(rcId.value)
      if (contractData.code === 200 && contractData.data) {
        if (contractData.data.partya === contractData.data.customerId) {
          partyaIs.value = true
          partyaType.value = contractData.data.cusType
        }
        if (contractData.data.partyb === contractData.data.customerId) {
          partybIs.value = true
          partybType.value = contractData.data.cusType
        }
        newContractForm.value = contractData.data
        optionsOrder.value = (contractData.data.ordOrderContractDto || []).map(
          v => {
            return {
              value: v.ordId,
              label: v.ordName
            }
          }
        )
        // 关联项目名称
        ordProjectName.value = contractData.data.projectName
        ordOrderContractEntitys.value = (
          contractData.data.ordOrderContractDto || []
        ).map(v => {
          return v.ordId
        })
        saler.value = contractData.data.salesmanName
        newContractForm.value.fileNames = (
          contractData.data.sysAttachFiles || []
        ).map(v => v.fileName)
        fileList.value = contractData.data.sysAttachFiles || []
        epibolyData.value = contractData.data.ordHroEntity
        checkData.value = contractData.data.ordProjectCheckEntity

        // 合同类别
        if (newContractForm.value.contractType === '0010') {
          newContractForm.value.contractType =
            newContractForm.value.businessType
        }

        if (!newContractForm.value.contractType) {
          newContractForm.value.contractType =
            newContractForm.value.businessType
        }
      }
      // 计划验收消息提醒回显
      const checkProData = await getLatestMsg({
        businessId: '合同-验收-' + rcId.value
      })
      if (checkProData.code === 200 && checkProData.data) {
        checkList.value.receiver = checkProData.data.receiver
        NotifyingOfficer.value = checkProData.data.receiverName
        checkList.value.list = checkProData.data.reminderMethod
          ? checkProData.data.reminderMethod.split(',')
          : []
        checkList.value.followTip = checkProData.data.followType
      }
      // 履约消息提醒回显
      if (newContractForm.value.pbAlonePay === '1') {
        const pbProData = await getLatestMsg({
          businessId: '合同-履约-' + rcId.value
        })
        if (pbProData.code === 200 && pbProData.data) {
          earnestMoney.value.receiver = pbProData.data.receiver
          person.value = pbProData.data.receiverName
          earnestMoney.value.list = pbProData.data.reminderMethod
            ? pbProData.data.reminderMethod.split(',')
            : []
          earnestMoney.value.time = pbProData.data.followDate
        }
      }
    } catch (error) {
      console.log(error)
    }
  }

  const { contract_type } = proxy.useDict('contract_type')
  companyList.value = await commonStore.getCompanyData()
  useTree.value = await commonStore.getUseTreeData()
  loading.value = false
  proxy.$nextTick(async () => {
    businessAttribute.value = arrayToTree(contract_type.value)
    // 履约保证金-跟进人员选择弹窗
    dialogParam.value = {
      type: '履约保证金',
      nodeKey: 'uuid',
      isDialog: false,
      data: [useTree.value[0]],
      multiple: true,
      defaultCheckedKeys: earnestMoney.value.receiver
        ? earnestMoney.value.receiver.split(',').map(v => 'U' + v)
        : [],
      checkStrictly: false,
      title: '人员选择'
    }
    // 验收计划-通知人员选择弹窗
    Notifyingdialog.value = {
      type: '通知人员',
      nodeKey: 'uuid',
      isDialog: false,
      data: [useTree.value[0]],
      multiple: true,
      defaultCheckedKeys: checkList.value.receiver
        ? checkList.value.receiver.split(',').map(v => 'U' + v)
        : [],
      checkStrictly: false,
      title: '人员选择'
    }
  })
}

// 数组转换树
/**
 * @params arr 输入数组
 * @params nodeKey 树唯一标识
 * @params parentId 父id
 *
 */
function arrayToTree(arr, nodeKey = 'value', parentId = 'parentId') {
  const mapObj = new Map()
  const result = []
  arr.forEach(v => {
    mapObj.set(v.value, v)
  })
  for (const [key, val] of mapObj) {
    if (val.parentId && mapObj.has(val.parentId)) {
      if (!mapObj.get(val.parentId).children) {
        mapObj.get(val.parentId).children = []
      }
      const some = mapObj.get(val.parentId).children.some(v => {
        return v.value === val.value
      })
      if (!some) {
        mapObj.get(val.parentId).children.push(val)
      }
    } else {
      result.push(mapObj.get(key))
    }
  }
  return result
}

init()
// 是否人力外包
const epiboly = computed(() => {
  return Number(newContractForm.value.businessType) === 1
})
function setTime() {
  if (!calcTime.value.time) {
    proxy.$modal.msgWarning('请选择日期')
    return
  }
  timeVisible.value = false
  checkData.value[indexRow.value].planAccepDate = calcTime.value.time
}
// 切换所属业务分类时
function changeBusinessType(val) {
  /**
   *  根据规则自动填写--industry 所属产业--businessClassify
   * */
}
// 提交表单
async function submit() {
  proxy.$refs['baseForm'].validate(async valid => {
    if (valid) {
      const response = verify()
      if (!response.result) {
        proxy.$modal.msgWarning(response.msg)
        return
      }
      const res = checkRemind()
      if (!res && checkData.value.length > 0) {
        return
      }
      if (newContractForm.value.pbAlonePay === '1') {
        if (!earnestMoney.value.time) {
          proxy.$modal.msgWarning(
            '该项目合同的履约保证金属于单独支付，请填写履约保证金跟进时间'
          )
          return
        }
        if (!earnestMoney.value.receiver) {
          proxy.$modal.msgWarning(
            '该项目合同的履约保证金属于单独支付，请选择履约保证金跟进人员'
          )
          return
        }
        if (!earnestMoney.value.list.length) {
          proxy.$modal.msgWarning(
            '该项目合同的履约保证金属于单独支付，请选择履约保证金提醒方式'
          )
          return
        }
        const resp = pbRemind()
        if (!resp) {
          return
        }
      }
      // 客户id
      if (partybIs.value && partybId.value) {
        newContractForm.value.customerId = partybId.value
      }
      if (partyaIs.value && partyaId.value) {
        newContractForm.value.customerId = partyaId.value
      }
      // 销售人员id
      if (newContractForm.value.salesmanId) {
        newContractForm.value.salesmanId = (
          newContractForm.value.salesmanId + ''
        ).replace(/U/g, '')
      }
      // 企业类型 --个人cusLink 企业customer
      if (['customer', 'cusLink'].indexOf(partyaType.value) > -1) {
        newContractForm.value.cusType = partyaType.value
      }
      if (['customer', 'cusLink'].indexOf(partybType.value) > -1) {
        newContractForm.value.cusType = partybType.value
      }
      if (isAdd.value) {
        newContractForm.value.ordHroEntity = epibolyData.value
        newContractForm.value.ordProjectCheckEntity = checkData.value.filter(
          v => {
            return v.stage && v.conditions && v.planAccepDate && v.planReturnSum
          }
        )
        newContractForm.value.ordOrderContractEntitys =
          ordOrderContractEntitys.value.map(v => {
            return { ordId: v }
          })

        // 合同类别为服务的情况
        if (
          newContractForm.value.contractType === '1' ||
          newContractForm.value.contractType === '2'
        ) {
          newContractForm.value.contractType = '0010'
        }
        const res = await contractInfoSave(newContractForm.value)
        if (res.code === 200 && res.data) {
          proxy.$modal.msgSuccess(res.msg)
          const id = res.data
          const url = `/sales/contract/contractDetail?id=${id}`
          if (checkList.value.receiver) {
            checkMsgData.value.forEach(v => {
              v.url = url
              v.businessId = '合同-验收-' + id
              addManage(v)
            })
          }
          if (
            earnestMoney.value.receiver &&
            newContractForm.value.pbAlonePay === '1'
          ) {
            pbMsgData.value.url = url
            pbMsgData.value.businessId = '合同-履约-' + id
            addManage(pbMsgData.value)
          }
          goBack()
        }
      } else {
        if (
          newContractForm.value.ordOrderContractDto &&
          newContractForm.value.ordOrderContractDto.length
        ) {
          newContractForm.value.ordOrderContractDto.filter(v => {
            const index = ordOrderContractEntitys.value.indexOf(v.ordId)
            if (index > -1) {
              ordOrderContractEntitys.value[index] = v
            }
          })
        }
        newContractForm.value.ordOrderContractEntitys =
          ordOrderContractEntitys.value.map(v => {
            if (typeof v === 'string') {
              return { ordId: v }
            } else {
              return v
            }
          })
        const result = checkData.value.some(v => {
          return (
            v.$cellEdit &&
            (v.stage || v.conditions || v.planAccepDate || v.planReturnSumk)
          )
        })
        if (result) {
          proxy.$modal.msgWarning('付款方式和条款相关内容未保存，请先前往保存')
          return
        }
        const epibolyResult = epibolyData.value.some(v => {
          return (
            v.$cellEdit &&
            (!v.workType || !v.peopleNum) &&
            (v.workType || v.peopleNum)
          )
        })
        if (epibolyResult) {
          proxy.$modal.msgWarning('人力外包情况相关内容未保存，请先前往保存')
          return
        }

        // 合同类别为服务的情况
        if (
          newContractForm.value.contractType === '1' ||
          newContractForm.value.contractType === '2'
        ) {
          newContractForm.value.contractType = '0010'
        }
        newContractForm.value.contractLevel = '航天科工外'
        const res = await contractInfoUpdate(newContractForm.value)
        if (res.code === 200) {
          const id = rcId.value
          const url = `/sales/contract/contractDetail?id=${id}`
          proxy.$modal.msgSuccess(res.msg)
          // if (checkList.value.receiver) {
          checkMsgData.value.forEach(v => {
            v.url = url
            v.businessId = '合同-验收-' + id
            addManage(v)
          })
          // }
          if (
            earnestMoney.value.receiver &&
            newContractForm.value.pbAlonePay === '1'
          ) {
            pbMsgData.value.url = url
            pbMsgData.value.businessId = '合同-履约-' + id
            addManage(pbMsgData.value)
          }
          goBack()
        }
      }
    }
  })
}
function goBack() {
  router.push({
    path: '/sales/contract/contractList'
  })
  useTagsViewStore().delView(router.currentRoute.value)
}
/**
 * @params 校验表单数据
 */
function verify() {
  if (fileList.value.length === 0) {
    proxy.$modal.msgError('请上传合同附件')
    return
  }
  if (
    !newContractForm.value.partya ||
    !newContractForm.value.partyaSig ||
    !newContractForm.value.partyb ||
    !newContractForm.value.partybSig
  ) {
    return {
      result: false,
      msg: '合同主体内容为必填内容，请填写完整合同主体内容'
    }
  }
  if (partyaIs.value === partybIs.value) {
    return {
      result: false,
      msg: '合同甲方、乙方不能同时选择内部单位或者客户'
    }
  }

  if (
    new Date(newContractForm.value.contractTimeBegin).getTime() >
    new Date(newContractForm.value.contractTimeEnd).getTime()
  ) {
    return { result: false, msg: '请选择合理的起止时间' }
  }
  if (checkData.value.length) {
    const name = checkData.value.filter(item => {
      if (
        (!item.planAccepDate ||
          !item.planReturnSum ||
          !item.stage ||
          !item.conditions) &&
        (item.planAccepDate ||
          item.planReturnSum ||
          item.stage ||
          item.conditions)
      ) {
        return item
      }
    })
    if (name.length) {
      return { result: !name.length, msg: '请输入付款方式和条款相关内容' }
    }
  }

  if (epibolyData.value.length) {
    const epiboly = epibolyData.value.filter(item => {
      if (
        (!item.workType || !item.peopleNum) &&
        (item.workType || item.peopleNum)
      ) {
        return item
      }
    })
    if (epiboly.length) {
      return { result: !epiboly.length, msg: '请输入人力外包情况相关内容' }
    }
  }

  return { result: true }
}

function changeDay(val, which = 'check') {
  if (which === 'check') {
    if (calcTime.value.num) {
      timeChange()
    }
  } else {
    if (earnestMoney.value.num) {
      timeChange('', 'pb')
    }
  }
}

// 工作日/自然日设置
function timeChange(val, which = 'check') {
  if (!newContractForm.value.sinTime) {
    proxy.$modal.msgWarning('请先设置签约时间')
    return
  }
  let time, type, num
  if (which === 'check') {
    type = calcTime.value.date
    num = calcTime.value.num
  } else {
    type = earnestMoney.value.date
    num = earnestMoney.value.num
  }
  if (type === '0') {
    // 工作日
    getWorkDay({
      dateStr: newContractForm.value.sinTime.substring(0, 10),
      dayNum: num
    }).then(res => {
      if (res.code === 200) {
        time = res.data.dateChar
        if (which === 'check') {
          calcTime.value.time = time
        } else {
          earnestMoney.value.time = time
        }
      }
    })
  } else {
    // 自然日
    time = format(
      new Date(
        new Date(newContractForm.value.sinTime).getTime() +
          num * 24 * 60 * 60 * 1000
      ),
      'yyyy-MM-dd'
    )
    if (which === 'check') {
      calcTime.value.time = time
    } else {
      earnestMoney.value.time = time
    }
  }
}

// 新增行
function rowAdd(type) {
  let obj = {
    id: checkData.value.length,
    stage: null,
    conditions: null,
    periodsNum: checkData.value.length + 1,
    planAccepRatio: null,
    planReturnSum: null,
    remark: null,
    isAdd: 'add',
    pcId: null,
    rcId: rcId.value || null,
    $cellEdit: true
  }
  if (type === 'crud') {
    // 选择销售人员后 默认通知人员为销售人员
    if (newContractForm.value.salesmanId && !checkList.value.receiver) {
      checkList.value.receiver = newContractForm.value.salesmanId
      checkList.value.list = ['0']
      NotifyingOfficer.value = saler.value
      Notifyingdialog.value.defaultCheckedKeys.push(checkList.value.receiver)
    }
    // 默认选择提前7天
    if (!checkList.value.followTip) {
      checkList.value.followTip = '4'
    }
    checkData.value.push(obj)
  } else {
    obj = {
      id: epibolyData.value.length,
      workType: null,
      peopleNum: null,
      isAdd: 'add',
      hroId: null,
      rcId: rcId.value || null,
      $cellEdit: true
    }
    epibolyData.value.push(obj)
  }
}

// 行保存
async function rowSave(row, index) {
  // row.isAdd标志判断是否第一次添加，执行save接口，后续编辑执行update接口
  // isAdd--判断 新增页面 或 编辑页面  新增页面调用主表（合同信息）新增接口，编辑调用子表（验收计划）新增接口
  try {
    if (row.isAdd === 'add') {
      if (isAdd.value) {
        newContractForm.value.ordProjectCheckEntity.push(row)
      } else {
        const checkRes = await checkProSave(row)
        row.pcId = checkRes.data
        proxy.$modal.msgSuccess('保存成功')
      }
    } else {
      const updateData = await checkProUpdate([row])
      proxy.$modal.msgSuccess('修改成功')
    }
    checkData.value[index] = row
    if (row.isAdd === 'add') {
      row.isAdd = 'edit'
    }
  } catch (error) {
    console.log(error)
  }
}

// 行删除
async function rowDelete(row, index) {
  try {
    if (row.pcId) {
      const res = await checkProDelete(row.pcId)
      if (res.code === 200) {
        proxy.$modal.msgSuccess(res.data)
        nextTick(() => {
          const newArr = checkData.value.filter(v => {
            if (v.pcId !== row.pcId) {
              v.periodsNum = v.$index + 1
              return v
            }
          })
          checkData.value = newArr
        })
        // if (!last) {
        if (!checkData.value.length) {
          checkList.value.receiver = ''
          NotifyingOfficer.value = ''
          checkList.value.followTip = ''
          Notifyingdialog.value.defaultCheckedKeys = []
          checkList.value.list = []
        }
        // 更新期次
        checkData.value.forEach(async v => {
          const updateData = await checkProUpdate([v])
        })
        // }
      }
    }
    if (isAdd.value) {
      newContractForm.value.ordProjectCheckEntity.splice(index, 1)
      nextTick(() => {
        checkData.value.forEach(v => {
          v.periodsNum = v.$index + 1
        })
        newContractForm.value.ordProjectCheckEntity.forEach(v => {
          v.periodsNum = v.$index + 1
        })
      })
      if (!checkData.value.length) {
        checkList.value.receiver = ''
        NotifyingOfficer.value = ''
        checkList.value.followTip = ''
        Notifyingdialog.value.defaultCheckedKeys = []
      }
    }
  } catch (error) {
    console.log(error)
  }
}

// 单元格点击事件
function handleRowClick(row, column, cell, event) {
  if (column && column.label === '付款日期' && row.$cellEdit) {
    if (!newContractForm.value.sinTime) {
      proxy.$modal.msgWarning('请先设置签约时间')
      return
    }
    timeVisible.value = true
    indexRow.value = row.$index
  }
}

// 外包表--保存
async function epibolyRowSave(row, index) {
  // row.isAdd标志判断是否第一次添加，执行save接口，后续编辑执行update接口
  // isAdd--判断 新增页面 或 编辑页面  新增页面调用主表（合同信息）新增接口，编辑调用子表（验收计划）新增接口
  try {
    row.workName = row.$workType
    if (row.isAdd === 'add') {
      if (isAdd.value) {
        newContractForm.value.ordHroEntity.push(row)
      } else {
        const checkRes = await epibolySave(row)
        row.hroId = checkRes.data
        proxy.$modal.msgSuccess('保存成功')
      }
    } else {
      const updateData = await epibolyUpdate(row)
      proxy.$modal.msgSuccess('修改成功')
    }
    epibolyData.value[index] = row
    if (row.isAdd === 'add') {
      row.isAdd = 'edit'
    }
  } catch (error) {
    console.log(error)
  }
}

// 外包表--删除
async function epibolyRowDelete(row, index) {
  try {
    if (!row.workType && !row.peopleNum) {
      return
    }
    if (row.hroId) {
      const res = await epibolyDelete(row.hroId)
      if (res.code === 200) {
        proxy.$modal.msgSuccess(res.data)
      }
    }
    if (isAdd.value) {
      newContractForm.value.ordHroEntity.splice(index, 1)
    }
  } catch (error) {
    console.error(error)
  }
}

function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}
// 上传合同
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      newContractForm.value.fileNames.push(res.data.fileName)
      fileList.value.push(res.data)
    } else {
      console.log(res.msg)
    }
  } catch (error) {
    console.error(error)
  }
}
// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        newContractForm.value.fileNames.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    console.log(error)
  }
}
// 弹窗关闭
function handleClose() {
  timeVisible.value = false
  calcTime.value = { date: '0', time: '' }
}
// selectDialog 选择数据 ---跟进人员
function selectData(val) {
  person.value = val.labelData.join(',')
  dialogParam.value.isDialog = false
  dialogParam.value.defaultCheckedKeys = val.defaultCheckedKeys
  earnestMoney.value.receiver = val.defaultCheckedKeys.join(',')
}

// selectDialog 选择数据 ---通知人员
function selectNotifying(val) {
  NotifyingOfficer.value = val.labelData.join(',')
  Notifyingdialog.value.isDialog = false
  Notifyingdialog.value.defaultCheckedKeys = val.defaultCheckedKeys
  checkList.value.receiver = val.defaultCheckedKeys.join(',')
}

// selectDialog 选择数据 ---销售人员
function selectSales(val) {
  saler.value = val.labelData.join(',')
  SaleDialog.value.isDialog = false
  SaleDialog.value.defaultCheckedKeys = val.defaultCheckedKeys
  newContractForm.value.salesmanId = val.defaultCheckedKeys.join(',')
}
// 激活dialog--甲方
function activatePartya() {
  dialogParamA.value = {
    isDialog: true,
    data: [],
    multiple: false,
    defaultCheckedKeys: newContractForm.value.partya
      ? [newContractForm.value.partya]
      : [],
    checkStrictly: false,
    title: '合同甲方选择',
    tabList: [
      {
        label: '企业客户',
        name: 'customer'
      },
      {
        label: '个人客户',
        name: 'cusLink'
      },
      {
        label: '内部单位',
        name: 'inner'
      }
    ],
    tabShow: true,
    nodeKey: 'id',
    defaultCheckedLabel: newContractForm.value.customerName,
    tabVal: partyaType.value ? partyaType.value : 'customer'
  }
}
// 激活dialog--乙方
function activatePartyb() {
  dialogParamB.value = {
    isDialog: true,
    data: [],
    multiple: false,
    defaultCheckedKeys: newContractForm.value.partyb
      ? [newContractForm.value.partyb]
      : [],
    checkStrictly: false,
    title: '合同乙方选择',
    tabList: [
      {
        label: '企业客户',
        name: 'customer'
      },
      {
        label: '个人客户',
        name: 'cusLink'
      },
      {
        label: '内部单位',
        name: 'inner'
      }
    ],
    tabShow: true,
    nodeKey: 'id',
    defaultCheckedLabel: newContractForm.value.customerName,
    tabVal: partybType.value ? partybType.value : 'inner'
  }
}

const partyaId = ref('')
const partybId = ref('')
/**
 *   选择类型
 *     企业客户   customer
 *     个人客户   cusLink
 *     内部单位   inner
 * */
const partyaType = ref('')
const partybType = ref('')
// 表格获取数据
function selectPartya(val) {
  console.log(val, 'partya 合同甲')
  newContractForm.value.partyaName = val.labelData[0]
  newContractForm.value.partya = val.defaultCheckedKeys[0]
  partyaType.value = val.tabVal
  // 选择合同方为客户时
  if (['customer', 'cusLink'].indexOf(val.tabVal) > -1) {
    // 切换客户时，关联数据重置
    if (newContractForm.value.customerId !== val.defaultCheckedKeys[0]) {
      ordProjectName.value = ''
      newContractForm.value.ordProjectId = ''
      ordOrderContractEntitys.value = []
      optionsOrder.value = []
      newContractForm.value.businessOpportunityTitle = null
      newContractForm.value.businessOpportunityId = null
    }
    newContractForm.value.customerId = val.defaultCheckedKeys[0]
    partyaId.value = val.defaultCheckedKeys[0]
    newContractForm.value.customerName = val.labelData[0] || ''
    partyaIs.value = true
  } else {
    partyaIs.value = false
    partyaId.value = ''
  }
}
// 关闭dialog
function closeDialogA() {
  dialogParamA.value.isDialog = false
}
function selectPartyb(val) {
  console.log(val, 'partyb')
  newContractForm.value.partybName = val.labelData[0]
  newContractForm.value.partyb = val.defaultCheckedKeys[0]
  partybType.value = val.tabVal
  // 选择合同方为客户时
  if (['customer', 'cusLink'].indexOf(val.tabVal) > -1) {
    // 切换客户时，关联项目重置
    if (newContractForm.value.customerId !== val.defaultCheckedKeys[0]) {
      if (!isFromProject.value) {
        ordProjectName.value = ''
      }
      newContractForm.value.ordProjectId = ''
      ordOrderContractEntitys.value = []
      optionsOrder.value = []
    }
    newContractForm.value.customerId = val.defaultCheckedKeys[0]
    partybId.value = val.defaultCheckedKeys[0]
    newContractForm.value.customerName = val.labelData[0]
    partybIs.value = true
  } else {
    partybIs.value = false
    partybId.value = ''
  }
}
function closeDialogB() {
  dialogParamB.value.isDialog = false
}

/**
 * 限制金额输入
 * @param type 表单绑定数据
 * @param newVal 输入内容
 */
function changeAmount(type, newVal) {
  if (newVal) {
    newContractForm.value[type] = newVal
      .replace(/[^\d.]/g, '') // 限制非数字输入
      .replace(/\.{2,}/g, '.') // 去除连续小数点
      .replace('.', 'xsd')
      .replace(/\./g, '')
      .replace('xsd', '.') //去除多余小数点
      .replace(/(\d+)(\.?)(\d{0,8})\d{0,}/g, '$1$2$3') //保留八位小数
  }
}

// 矫正输入金额
function blurAmount(type) {
  if (newContractForm.value[type]) {
    newContractForm.value[type] = newContractForm.value[type]
      .replace(/^(\d+)\.$/g, '$1')
      .replace(/^(\d+)\.[0]+$/, '$1')
    newContractForm.value[type] = parseFloat(newContractForm.value[type])
    newContractForm.value[type] = newContractForm.value[type] + '' // 变回为字符串
  }
}

// 项目计划验收消息提醒
function checkRemind() {
  let resp = true
  checkMsgData.value = []
  for (let i = 0; i < checkData.value.length; i++) {
    if (
      checkData.value[i].stage &&
      checkData.value[i].conditions &&
      checkData.value[i].planAccepDate &&
      checkData.value[i].planReturnSum
    ) {
      const obj = {}
      const num = [0, 1, 3, 5, 7][Number(checkList.value.followTip)]
      const time =
        checkList.value.followTip && (num || num === 0)
          ? format(
              new Date(
                new Date(checkData.value[i].planAccepDate).getTime() -
                  num * 24 * 60 * 60 * 1000
              ),
              'yyyy-MM-dd 00:00:00'
            )
          : ''
      obj.receiver = checkList.value.receiver
        ? (checkList.value.receiver + '' || '').replace(/U/gi, '')
        : checkList.value.receiver
      obj.sendTime = time
      obj.content =
        newContractForm.value.contractName +
        '验收计划' +
        checkData.value[i].periodsNum +
        '期'
      obj.reminderMethod =
        !checkList.value.list ||
        (checkList.value.list && checkList.value.list.length === 0)
          ? ''
          : checkList.value.list.toString()
      obj.impSign = '2'
      obj.serviceType = '6'
      obj.urgFlag = '1'
      obj.receiverName = NotifyingOfficer.value
      obj.followType = checkList.value.followTip
        ? checkList.value.followTip
        : null
      obj.urlName = '前往详情'
      obj.title = `${newContractForm.value.contractName}${checkData.value[i].periodsNum}期验收计划`
      obj.type = '0'
      obj.sender = userStore.user.nickName
      // 项目验收计划
      console.log(obj, 'obj')
      const result = pushNotifications(obj, ['receiver', 'followType'])
      if (!obj.reminderMethod && obj.receiver && obj.followType) {
        proxy.$modal.msgWarning(
          '付款方式和条款消息提醒方式未选择，请先填写完整'
        )
        resp = false
        return
      }
      if (obj.receiver && !obj.followType) {
        proxy.$modal.msgWarning(
          '付款方式和条款消息验收提醒未选择，请先填写完整'
        )
        resp = false
        return
      }
      if (!obj.receiver && obj.followType) {
        proxy.$modal.msgWarning(
          '付款方式和条款消息通知人员未选择，请先填写完整'
        )
        resp = false
        return
      }
      // if (!result) {
      //   proxy.$modal.msgWarning(
      //     '付款方式和条款消息提醒存在未填内容，请先填写完整'
      //   )
      //   resp = false
      //   return
      // } else {
      checkMsgData.value.push(obj)
      // }
    }
  }
  if (checkData.value.length === 0) {
    checkMsgData.value.push({
      receiver: null,
      followType: null,
      reminderMethod: null
    })
  }
  return resp
}

// 履约保证金跟进任务消息提醒
function pbRemind() {
  if (newContractForm.value.pbAlonePay) {
    const obj = {}
    // 履约保证金跟进任务
    let resp = true
    // const num = [0, 1, 3, 5, 7][Number(earnestMoney.value.followTip)]
    const time = earnestMoney.value.time
      ? format(
          new Date(new Date(earnestMoney.value.time)),
          'yyyy-MM-dd 00:00:00'
        )
      : ''
    obj.receiver = (earnestMoney.value.receiver + '' || '').replace(/U/gi, '')
    obj.content =
      '请跟进' + newContractForm.value.contractName + '的履约保证的回款情况' //earnestMoney.value.content
    obj.sendTime = time
    obj.reminderMethod =
      !earnestMoney.value.list ||
      (earnestMoney.value.list && earnestMoney.value.list.length === 0)
        ? ''
        : earnestMoney.value.list.toString()
    obj.impSign = '2'
    obj.serviceType = '6'
    obj.urgFlag = '1'
    obj.receiverName = person.value
    obj.followType = earnestMoney.value.followTip
      ? earnestMoney.value.followTip
      : null
    obj.followDate = earnestMoney.value.time
    obj.urlName = '前往详情'
    obj.title = `${newContractForm.value.contractName}的履约保证金跟进提醒`
    obj.type = '0'
    obj.sender = userStore.user.nickNamee
    // 履约保证金
    const result = pushNotifications(obj, ['receiver', 'sendTime'])
    if (!result) {
      proxy.$modal.msgWarning('履约保证金消息提醒存在未填内容，请先填写完整')
      resp = false
    } else {
      pbMsgData.value = obj
    }
    return resp
  }
}

async function queryOrder(val) {
  if (!newContractForm.value.customerId) {
    proxy.$modal.msgWarning('请先选择合同主体甲乙方')
    return
  }
  if (partyaIs.value === partybIs.value) {
    proxy.$modal.msgWarning('合同甲方、乙方不能同时选择内部单位或者客户')
    return
  }
  if (partybIs.value && partybId.value) {
    newContractForm.value.customerId = partybId.value
  }
  if (partyaIs.value && partyaId.value) {
    newContractForm.value.customerId = partyaId.value
  }
  const orderList = await getOrderList({
    customerId: newContractForm.value.customerId,
    title: val,
    pageSize: 20
  })
  if (orderList.code === 200) {
    optionsOrder.value = (orderList.rows || []).map(v => ({
      label: v.title,
      value: v.id
    }))
  }
}

function salerSaleDialog() {
  SaleDialog.value = {
    nodeKey: 'uuid',
    isDialog: true,
    data: [useTree.value[0]],
    multiple: false,
    defaultCheckedKeys: [
      'U' + (newContractForm.value.salesmanId + '' || '').replace(/U/g, '')
    ],
    checkStrictly: false,
    title: '人员选择'
  }
}

/*** +++++++++++++++++++++++++   关联项目   +++++++++++++++++++++++++***/
// 打开弹窗
const proParams = ref({})
const businessDiaParams = ref({}) //关联商机 弹出框的参数
function activeDialog(type) {
  const id = newContractForm.value.customerId
  if (!id) {
    proxy.$modal.msgError('请先选择合同甲乙方')
    return false
  }
  if (partyaIs.value === partybIs.value) {
    proxy.$modal.msgWarning('合同甲方、乙方不能同时选择内部单位或者客户')
    return
  }
  if (partybIs.value && partybId.value) {
    newContractForm.value.customerId = partybId.value
  }
  let ids = []
  if (type == 'business') {
    //关联商机 /*商机列表跳转过来  gbq  2024/6/19 */
    ids = newContractForm.value.businessOpportunityId + ''
    businessDiaParams.value = {
      visible: true, // 显示dialog
      businessId: id, // 根据id查询合同列表
      businessName:
        ['customer', 'cusLink'].indexOf(partyaType.value) > -1
          ? newContractForm.value.partyaName
          : newContractForm.value.partybName,
      multiple: false, // 是否多选
      defaultSelect: ids ? ids : [] // 默认选择数据
    }
  } else {
    //关联项目
    ids = newContractForm.value.ordProjectId
    proParams.value = {
      visible: true, // 显示dialog
      businessId: id, // 根据id查询合同列表
      businessName:
        ['customer', 'cusLink'].indexOf(partyaType.value) > -1
          ? newContractForm.value.partyaName
          : newContractForm.value.partybName,
      multiple: false, // 是否多选
      defaultSelect: ids ? ids : [] // 默认选择数据
    }
  }
}

// 弹窗确认完成回调
function proRelatedOver(val) {
  console.log(val, '查看回调-项目')
  if (val) {
    const name = proParams.value.multiple
      ? val.map(v => v.proName).toString() || ''
      : val.proName

    const ids = proParams.value.multiple
      ? val.map(v => v.projectId) || []
      : val.projectId

    newContractForm.value.ordProjectId = ids
    ordProjectName.value = proParams.value.multiple
      ? val.map(v => v.proName)
      : name
  }
  proCloseDialog('project')
}
//关联商机 /*商机列表跳转过来  gbq  2024/6/19 */
function businessDiaRelatedOver(val) {
  console.log(val, '查看回调-商机1')
  if (val) {
    newContractForm.value.businessOpportunityTitle = val.titleName
    newContractForm.value.businessOpportunityId = val.id
  }
  proCloseDialog('business')
}
// 关闭弹窗
function proCloseDialog(type) {
  if (type == 'business') {
    //关联商机 /*商机列表跳转过来  gbq  2024/6/19 */
    businessDiaParams.value.visible = false
  } else {
    //关联项目
    proParams.value.visible = false
  }
}

// el-input clear函数
function clearAll(type) {
  if (type == 'business') {
    /*商机列表跳转过来  gbq  2024/6/19 */
    //关联商机
    newContractForm.value.businessOpportunityTitle = null
    newContractForm.value.businessOpportunityId = null
  } else {
    //关联项目
    newContractForm.value.ordProjectId = null
    ordProjectName.value = ''
  }
}
/*** +++++++++++++++++++++++++   关联订单   +++++++++++++++++++++++++***/

const orderParams = ref({})
// 打开弹窗
function activeOrdDialog() {
  const id = newContractForm.value.customerId
  if (!id) {
    proxy.$modal.msgError('请先选择合同甲乙方')
    return false
  }
  if (partyaIs.value === partybIs.value) {
    proxy.$modal.msgWarning('合同甲方、乙方不能同时选择内部单位或者客户')
    return
  }
  if (partybIs.value && partybId.value) {
    newContractForm.value.customerId = partybId.value
  }
  if (partyaIs.value && partyaId.value) {
    newContractForm.value.customerId = partyaId.value
  }
  const ids = ordOrderContractEntitys.value || newContractForm.value.orderId
  orderParams.value = {
    visible: true, // 显示dialog
    businessId: id, // 根据id查询合同列表
    businessName: newContractForm.value.customerName,
    multiple: true, // 是否多选
    defaultSelect: ids ? ids : [] // 默认选择数据
  }
}

function ordRelatedOver(val) {
  console.log(val, 'order')
  if (val) {
    const name = orderParams.value.multiple
      ? val.map(v => v.orderTitle).toString() || ''
      : val.orderTitle

    const ids = orderParams.value.multiple
      ? val.map(v => v.orderId) || []
      : val.orderId

    ordOrderContractEntitys.value = ids
    optionsOrder.value = orderParams.value.multiple
      ? val.map(v => ({ value: v.orderId, label: v.orderTitle }))
      : name
  }
  ordCloseDialog()
}
// 关闭弹窗
function ordCloseDialog() {
  orderParams.value.visible = false
}

watch(
  () => newContractForm.value.contractTimeBegin,
  val => {
    if (!newContractForm.value.sinTime) {
      newContractForm.value.sinTime = newContractForm.value.contractTimeBegin
    }
  }
)

watch(
  () => newContractForm.value.contractType,
  async (newVal, oldVal) => {
    if (newVal) {
      if (newVal === '1' || newVal === '2') {
        newContractForm.value.businessType = newVal
      } else {
        newContractForm.value.businessType = '0'
      }
    }
  }
)

watch(
  () => props.id,
  async (newVal, oldVal) => {
    if (newVal) {
      init()
    }
  }
)

// 项目跳转到合同
const isFromProject = ref(false)
watch(
  () => route.query.ordProjectId,
  val => {
    if (val) {
      isFromProject.value = true
      ordProjectName.value = route.query.ordProjectName
      newContractForm.value = {
        contractName: null,
        contractNum: null,
        businessType: '2',
        contractSum: null,
        pb: null,
        pbAlonePay: '1',
        partya: route.query.customerId,
        partyaSig: null,
        partyb: null,
        partybSig: null,
        ordProjectId: val,
        contractTimeBegin: null,
        contractTimeEnd: null,
        salesmanId: null,
        sinTime: null,
        remark: null,
        fileNames: [],
        ordProjectCheckEntity: [], // 验收计划数据
        ordHroEntity: [], // 人力外包数据
        ordOrderContractEntitys: [], // 关联订单数据
        customerId: route.query.customerId, // 客户ID
        customerName: route.query.customerName // 名称
      }
      partyaIs.value = true
      newContractForm.value.partyaName = route.query.customerName
    } else {
      // isFromProject.value = false
    }
  },
  {
    immediate: true
  }
)
/*商机列表跳转过来  gbq  2024/6/19 start*/
watch(
  () => route.query.t,
  val => {
    if (val) {
      newContractForm.value.businessOpportunityTitle = route.query.n //商机标题
      newContractForm.value.businessOpportunityId = route.query.id //商机id
      newContractForm.value.partyaName = route.query.c //客户名称
      newContractForm.value.partya = route.query.cI //客户id
      newContractForm.value.customerId = route.query.cI //客户id
      newContractForm.value.customerName = route.query.c //客户名称
      partyaId.value = route.query.cI
      partyaIs.value = true
      businessParams.value = {
        type: route.query.t,
        id: route.query.id,
        customerName: route.query.c, //客户名称
        customerId: route.query.cI, //客户id
        titleName: route.query.n
      }
      newContractForm.value.businessCategorize = '财税大客户销售' //所属业务分类:
    } else {
      businessParams.value = {}
    }
    console.log(businessParams.value, '商机跳转')
  },
  {
    immediate: true
  }
)
/*商机列表跳转过来  end*/
</script>

<style lang="scss" scoped>
.newContract {
  @apply relative;
  .part {
    margin: 10px 0;
  }
  .requiredTip {
    @apply absolute top-30px right-50px text-gray-400;
    font-size: 14px;
  }

  .font-15 {
    @apply pr-10px flex items-center justify-end text-gray-800;
    font-size: 13px;
    text-align: right;
  }

  textarea {
    resize: none;
  }

  :deep div.el-card__body {
    padding: 15px 20px 0px 20px !important;

    .avue-crud__menu {
      min-height: 0;
    }
  }

  .checkPlan {
    :deep .el-form-item__content {
      width: 100%;

      .el-tooltip__trigger {
        width: 100%;
      }
    }

    :deep .avue-crud {
      width: 80%;
    }
  }

  .statisticsFrom {
    width: 80%;
    margin: 0 auto;
    @apply mt-20px;
  }

  .earnesMoney {
    .el-select.smallInput {
      :deep .el-input__inner {
        width: 80px;
      }
    }
  }
  :deep(.htfj .el-form-item__label::before) {
    content: '*';
    color: var(--el-color-danger);
    margin-right: 4px;
  }
  .pbTip::before {
    content: '*';
    color: var(--el-color-danger);
    margin-right: 4px;
  }
}

:deep .el-overlay-dialog {
  @apply flex justify-center items-center;
}

.timeDiglog {
  .timeCalc {
    @apply pr-10px flex items-center justify-end text-gray-800;
    font-size: 13px;
    text-align: right;
  }
}

:deep .part .el-select {
  width: 100%;
}

:deep .el-date-editor.el-input {
  width: 100%;
}

:deep(.checkPlan .el-form-item__label::before) {
  margin-right: -7px !important;
}
:deep(.checkPlan .el-input__wrapper) {
  padding-right: 15px;
}
:deep(.checkPlan .el-input-number__decrease) {
  display: none;
}

:deep(.checkPlan .el-input-number__increase) {
  display: none;
}

:deep(.checkPlan .el-input-number) {
  width: inherit;
}

:deep(.el-input__inner::-webkit-input-placeholder) {
  text-align: left;
}
:deep(.el-loading-mask) {
  height: 100vh;
}
</style>
